package com.demo.base64;




import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author wangning
 * @date 2023/5/5 17:17
 */
public class Base64Demo {
    public static void main(String[] args) {

    }

    public void test01() throws UnsupportedEncodingException {
        // 加密
        String base64 = Base64.getEncoder().encodeToString("待加密字符串".getBytes(StandardCharsets.UTF_8));
        System.out.println("base64 = " + base64);
        //5b6F5Yqg5a+G5a2X56ym5Liy
        //5b6F5Yqg5a+G5a2X56ym5Liy

        // 解密
        String str = new String(Base64.getDecoder().decode("5b6F5Yqg5a+G5a2X56ym5Liy"), StandardCharsets.UTF_8);
        System.out.println("str = " + str);

    }

    public void file2base64() {
        File file = new File("C:/Users/wangning/Desktop/20230506090941_monthly.xlsx");
        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputStream.read(buffer);
            inputStream.close();
            Base64.Encoder encoder = Base64.getEncoder();
            String base64 = encoder.encodeToString(buffer);
            System.out.println("base64 = " + base64);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
